package model

import (
	"errors"
	"fmt"
	"time"
	"tools-api/src/common/db/database"
	"xorm.io/xorm"
)

// BookTypes 类别
type BookTypes struct {
	Id         int64     `json:"id"`
	Uuid       string    `json:"-"`
	Key        string    `json:"key"`
	Name       string    `json:"name"`
	Type       int       `json:"-"`    // 1:支出 2:收入
	Sort       int       `json:"sort"` // 排序
	CreatedAt  time.Time `xorm:"created" json:"-"`
	ModifiedAt time.Time `xorm:"updated" json:"-"`
	DeleteMark int       `xorm:"delete_mark" json:"-"`
}

// BookTypesResult 返回结果
type BookTypesResult struct {
	Id      int64  `json:"id"`
	Key     string `json:"key"`
	Name    string `json:"name"`
	Sort    int    `json:"sort"` // 排序
	NotZero bool   `json:"not_zero" xorm:"tinyint(1)"`
}

// CopyFromDefault 新建用户，复制默认类别组
func (BookTypes) CopyFromDefault(uuid string) error {
	sql := fmt.Sprintf("insert into book_types (uuid, `key`, `name`, type, sort) select '%s', `key`, `name`, type, sort from book_types where uuid= '0' and delete_mark = 0", uuid)
	res, err := database.JCJEngine.Exec(sql)
	if err != nil {
		return err
	}
	affectedRows, _ := res.RowsAffected()
	if affectedRows == 0 {
		return errors.New("拷贝失败")
	}
	return nil
}

func (item BookTypes) Create() int64 {
	_ = database.Session(database.JCJEngine.NewSession(), func(session *xorm.Session) error {
		var sort int // 自动计算排序值
		_, _ = session.Table(BookTypes{}).Where("uuid = ? and type=?", item.Uuid, item.Type).Select("(IFNULL(MAX(sort), 0) + 1) as sort").Get(&sort)
		item.Sort = sort
		_, _ = session.Insert(&item)
		return nil
	})
	return item.Id
}

func (BookTypes) GetTypesByType(uuid string, _type int) []BookTypesResult {
	list := make([]BookTypesResult, 0)
	_ = database.JCJEngine.Table(BookTypes{}).Cols("id, key, name, sort").
		Where("uuid=? and type=? and delete_mark=0", uuid, _type).
		Asc("sort").
		Find(&list)
	return list
}

// GetTypesByType2 增加数量统计
func (BookTypes) GetTypesByType2(uuid string, _type int) []BookTypesResult {
	list := make([]BookTypesResult, 0)
	_ = database.JCJEngine.Table(BookTypes{}).Alias("t").
		Join("LEFT", []string{"book_detail", "d"}, "d.types_id = t.id AND d.delete_mark=0").
		Select("t.id, t.key, t.name, t.sort, case when COUNT(d.id) > 0 then 1 else 0 end as not_zero").
		Where("t.uuid=? and t.type=? and t.delete_mark=0", uuid, _type).
		GroupBy("t.id").
		Asc("t.sort").
		Find(&list)
	return list
}

// Delete 虚拟删除
func (BookTypes) Delete(session *xorm.Session, uuid string, id int64) error {
	rows, err := session.Where("id=? and uuid=?", id, uuid).Cols("delete_mark").Update(&BookTypes{DeleteMark: 1})
	if err != nil {
		return err
	}
	if rows == 0 {
		return errors.New("无权限")
	}
	return nil
}
